#include "login.h"
#include "../gateway.h"

Login::Login()
: m_state(STATE_START)
, m_nextState(STATE_LOGIN)
{
}

Login::~Login()
{
}

void Login::Update()
{
	if(m_nextState != m_state)
	{
		SetState(m_nextState);
	}

	switch(m_state)
	{
	case STATE_LOGIN:
		if(LOGINRESULT_SUCCESS == m_loginResult)
			SetState(STATE_END);
		else
			SetState(STATE_KICKOUT);
		break;

	case STATE_KICKOUT:
		sGateServer.Kickout(m_gateway->GetUid());
		m_loginResult = sGateServer.Login(m_gateway->GetUid(), m_gateway);
		if(LOGINRESULT_SUCCESS == m_loginResult)
			SetState(STATE_END);
		break;

	default:
		break;
	}
}

void Login::SetState(State state)
{
	switch(state)
	{
	case STATE_LOGIN:
		{
			BlockTree tree;
			tree.LoadFromNetPacket(*m_packet);

			NodeIterator it;
			BlockNode* node = tree.FindFirstChild(Def::KEY_USERNAME, it);
			if(node != NULL) m_gateway->SetUid(node->GetString());

			node = tree.FindNextChild(Def::KEY_PASSWORD, it);
			if(node != NULL) m_gateway->SetPassword(node->GetString());

			m_loginResult = sGateServer.Login(m_gateway->GetUid(), m_gateway);
		}
		break;

	case STATE_END:
		{
			NetPacket sendPacket(Def::OPCODE_SC_LOGIN, this);
			m_gateway->PushSendPacket(sendPacket, NULL);

			m_bDone = true;
			m_gateway->SetState(Gateway::STATE_RUN);
		}
		break;
	}

	m_state = state;
	m_nextState = m_state;
}